﻿<?php
class FormProcessor_UserRegistration extends FormProcessor {
	protected $db = null;
	public $user = null;
	
	public function __construct($db) {
		parent::__construct();
		$this->user = new DatabaseObject_User($db);
		$this->user->type = 'member';
	}
	
	public function process(Zend_Controller_Request_Abstract $request) {
		//验证用户名
		$this->username = $this->sanitize($request->getPost('username'));
		if (strlen($this->username) == 0) {
			$this->addError('username', '请输入用户名');
		} elseif (!DatabaseObject_User::IsValidUserName($this->username)) {
			$this->addError('username', '用户名不合法');
		} elseif ($this->user->userNameExists($this->username)) {
			$this->addError('username', '用户名已存在');
		} else {
			$this->user->username = $this->username;
		}
		
		//密码
		$this->password = $this->sanitize($request->getPost('password'));
		if (strlen($this->password) == 0 ) {
			$this->addError('password', '请输入密码');
		}
		$this->comfirm = $this->sanitize($request->getPost('comfirm'));
		if (strlen($this->comfirm) == 0 ) {
			$this->addError('comfirm', '请重复输入密码');
		} elseif($this->password != $this->comfirm) {
			$this->addError('comfirm', '两次密码输入不同');	
		} else {
			$this->user->password = $this->password;
		}
		
		//邮箱
		$this->email = $this->sanitize($request->getPost('email'));
		$validator = new Zend_Validate_EmailAddress();
		
		if(strlen($this->email) == 0) {
			$this->addError('email', '请输入邮箱');
		} elseif (!$validator->isValid($this->email)) {
			$this->addError('email', '邮箱不合法');
		} else {
			$this->user->email = $this->email;
		}
		//验证码
		$session = new Zend_Session_Namespace('captcha');
		$this->captcha = $this->sanitize($request->getPost('captcha'));
		if ($this->captcha != $session->captchaWord) {
			$this->addError('captcha', '验证码错误');
		}
		
		//如果无错保存到数据库
		if (!$this->hasError()) {
			$this->user->regtime = time();
			$this->user->save();
		}
		
		unset($session->captchaWord);
		//return true
		return !$this->hasError();
	}
}
?>